package edu.sandau.b230151.b23015135.controller;

import edu.sandau.b230151.b23015135.model.Book;
import edu.sandau.b230151.b23015135.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookService bookService;

    public static Map<String, Book> books = new HashMap<>();


    @RequestMapping("/search")
    public String search(ModelMap map, Book book) {
        if ("".equals(book.getName())) {
            book.setName(null);
        }
        if ("".equals(book.getAuthor())) {
            book.setAuthor(null);
        }
        List<Book> books = bookService.findAll(book);

        map.put("bookList", books);

        return "book/list";
    }

    @RequestMapping("/list")
    public String list(ModelMap map, Book book) {
        if ("".equals(book.getName())) {
            book.setName(null);
        }
        if ("".equals(book.getAuthor())) {
            book.setAuthor(null);
        }
        map.put("bookList", bookService.findAll(book));

        return "book/list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        bookService.deleteById(id);//数据库删除
        return "redirect:/book/list";//重定向
    }

    @RequestMapping("create")
    public String create() {
        return "/book/create";
    }

    @RequestMapping("save")
    public String save(Book s) {
        if (s.getId() == null) {
            s.setId(UUID.randomUUID().toString());
            bookService.save(s);//数据库保存
        } else {
            bookService.update(s);
        }

        return "redirect:/book/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id, ModelMap map) {
        Book s = bookService.getReferenceById(id);//数据库查询
        map.put("book", s);
        return "/book/update";
    }
}

